package cnsatmsmart.automation.mmi.view.dialogs;

import cnsatmsmart.automation.mmi.helper.utilities.GlobalEnvVars;
import java.awt.Image;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
import org.jdesktop.application.Action;

/**
 *
 * @author SIK - PTIK, BPPT
 */
public class connectionSetting extends javax.swing.JDialog {

    /** Constructor - user defined constructor, no default constructor
     * membuat form connectionSetting yang baru
     * @param parent jendela yang memanggilnya
     * @param modal ada atau tidaknya dialog ini
     */
        public connectionSetting(java.awt.Frame parent, boolean modal) {
            super(parent, modal);
            initComponents();

            Image frameIcon = GlobalEnvVars.kit.getImage(getClass().getResource("/cnsatmsmart/resources/"+GlobalEnvVars.icon));
            setIconImage(frameIcon);
            setTitle("Connection Settings");

            ButtonGroup bg = new ButtonGroup();
            bg.add(rbMulticast);
            bg.add(rbUnicast);

            if (!InitIfFileExits())
            {
                txtPort.setText(GlobalEnvVars.port+"");
                txtServer.setText(GlobalEnvVars.ipServer);

                if (GlobalEnvVars.isUnicast)
                {
                    txtBindInterface.setEnabled(false);
                    rbUnicast.setSelected(true);
                }
                else
                {
                    txtBindInterface.setEnabled(true);
                    rbMulticast.setSelected(true);
                }
            }

            setResizable(false);
        }

    /* method - method lain yang dimiliki oleh kelas connectionSetting */
        /**
         *
         * @return
         */
        public boolean InitIfFileExits()
        {
            boolean fileExist = false;
            File f = new File ("conn_rec.txt");
            if (f.exists())
            {
                fileExist = true;
                readFromFile("conn_rec.txt");
            }
            return fileExist;
        }

        private List validateInput()
        {
            List errorMsg = new Vector();

            //IPServer
            String str = txtServer.getText();
            if (str.isEmpty()) {
                errorMsg.add("IP Server field is empty.");
            } else {
                //mengecek apakah address multicastnya
                InetAddress addr;
                try {
                    addr = InetAddress.getByName(str);

                    if (addr.isMulticastAddress()) {
                        if (rbUnicast.isSelected()) {
                            errorMsg.add("IP Server is not a unicast address.");
                        }
                    } else {
                        if (rbMulticast.isSelected()) {
                            errorMsg.add("IP Server is not a multicast address.");
                        }
                    }
                } catch (UnknownHostException uhe) {
                    errorMsg.add("IP Server is not valid.");
                }
            }

            //port
            str = txtPort.getText();
            int port = 0;
            if (str.isEmpty()) {
                errorMsg.add("Port field is empty.");
            } else {
                try {
                    port = Integer.parseInt(str);
                    if (port < 1024 || port > 65535) {
                        errorMsg.add("Port field must be between 1024 and 65535.");
                    }
                } catch (NumberFormatException nfe) {
                    errorMsg.add("Port field must be an integer.");
                }
            }

            return errorMsg;
        }

        /**
         * Prints some data to a file using a BufferedWriter
         * @param filename
         * @param IP
         * @param Port
         * @param BindInterface
         * @param isUnicast
         */
        public void writeToFile(String filename, String IP, String Port, String BindInterface, boolean isUnicast) {

            BufferedWriter bufferedWriter = null;

            try {
                //Construct the BufferedWriter object
                bufferedWriter = new BufferedWriter(new FileWriter(filename));

                //Start writing to the output stream
                if (IP == null || IP.equals("")) bufferedWriter.write("NULL");
                else bufferedWriter.write(IP);
                bufferedWriter.newLine();
                if (Port == null || Port.equals("")) bufferedWriter.write("NULL");
                else bufferedWriter.write(Port);
                bufferedWriter.newLine();
                if (BindInterface == null || BindInterface.equals("")) bufferedWriter.write("NULL");
                else bufferedWriter.write(BindInterface);
                bufferedWriter.newLine();
                if (isUnicast) bufferedWriter.write("UNICAST");
                else bufferedWriter.write("MULTICAST");
                bufferedWriter.newLine();
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                //Close the BufferedWriter
                try {
                    if (bufferedWriter != null) {
                        bufferedWriter.flush();
                        bufferedWriter.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

        /**
         * Reads text from a file line by line
         * @param filename
         */
        public void readFromFile(String filename) {
            BufferedReader bufferedReader = null;
            try {
                //Construct the BufferedReader object
                bufferedReader = new BufferedReader(new FileReader(filename));

                String line = null;
                int i = 0;

                while ((line = bufferedReader.readLine()) != null) {
                    if (i == 0)
                    {
                        if (line.equals("NULL")) txtServer.setText("");
                        txtServer.setText(line);
                    }
                    else if (i == 1)
                    {
                        if (line.equals("NULL")) txtPort.setText("");
                        else txtPort.setText(line);
                    }
                    else if (i == 2)
                    {
                        if (line.equals("NULL")) txtBindInterface.setText("");
                        else txtBindInterface.setText(line);
                    }
                    else if (i == 3)
                    {
                        if (line.equals("UNICAST"))
                        {
                            rbUnicast.setSelected(true);
                            txtBindInterface.setEnabled(false);
                        }
                        else
                        {
                            rbMulticast.setSelected(true);
                            txtBindInterface.setEnabled(true);
                        }
                    }
                    i++;
                }

            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                //Close the BufferedReader
                try {
                    if (bufferedReader != null)
                        bufferedReader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtServer = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPort = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtBindInterface = new javax.swing.JTextField();
        rbMulticast = new javax.swing.JRadioButton();
        rbUnicast = new javax.swing.JRadioButton();
        btnSave = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(cnsatmsmart.CNSATMSMARTApp.class).getContext().getResourceMap(connectionSetting.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        txtServer.setText(resourceMap.getString("txtServer.text")); // NOI18N
        txtServer.setName("txtServer"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        txtPort.setText(resourceMap.getString("txtPort.text")); // NOI18N
        txtPort.setName("txtPort"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        txtBindInterface.setText(resourceMap.getString("txtBindInterface.text")); // NOI18N
        txtBindInterface.setName("txtBindInterface"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(cnsatmsmart.CNSATMSMARTApp.class).getContext().getActionMap(connectionSetting.class, this);
        rbMulticast.setAction(actionMap.get("onMulticast")); // NOI18N
        rbMulticast.setText(resourceMap.getString("rbMulticast.text")); // NOI18N
        rbMulticast.setName("rbMulticast"); // NOI18N

        rbUnicast.setAction(actionMap.get("onUnicast")); // NOI18N
        rbUnicast.setText(resourceMap.getString("rbUnicast.text")); // NOI18N
        rbUnicast.setName("rbUnicast"); // NOI18N

        btnSave.setAction(actionMap.get("clickSave")); // NOI18N
        btnSave.setText(resourceMap.getString("btnSave.text")); // NOI18N
        btnSave.setName("btnSave"); // NOI18N

        btnCancel.setAction(actionMap.get("clickCancel")); // NOI18N
        btnCancel.setText(resourceMap.getString("btnCancel.text")); // NOI18N
        btnCancel.setName("btnCancel"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(rbMulticast)
                        .addGap(18, 18, 18)
                        .addComponent(rbUnicast))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtBindInterface, javax.swing.GroupLayout.DEFAULT_SIZE, 291, Short.MAX_VALUE)
                                .addContainerGap())
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(135, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 157, Short.MAX_VALUE)
                                .addComponent(btnSave)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCancel)
                                .addGap(16, 16, 16))))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtBindInterface, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rbMulticast)
                    .addComponent(rbUnicast)
                    .addComponent(btnCancel)
                    .addComponent(btnSave))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * action untuk rbUnicast
     */
    @Action
    public void onUnicast()
    {
        if (rbUnicast.isSelected())
            txtBindInterface.setEnabled(false);
    }

    /**
     * action untuk rbMulticast
     */
    @Action
    public void onMulticast()
    {
        if (rbMulticast.isSelected())
            txtBindInterface.setEnabled(true);
    }

    /**
     * action untuk btnSave
     */
    @Action
    public void clickSave()
    {
        List listError = validateInput();

        if (listError != null && listError.size()>0)
        {
            StringBuffer messageBuffer = new StringBuffer();
            Iterator messages = listError.iterator();

            while (messages.hasNext()) {
                messageBuffer.append((String) messages.next());
                messageBuffer.append("      " + System.getProperty("line.separator"));
            }

            JOptionPane.showMessageDialog(this, messageBuffer.toString(),
                    "Input Data Error", JOptionPane.ERROR_MESSAGE);

            return;
        }
        else
        {
            GlobalEnvVars.port = Integer.parseInt(txtPort.getText().toString());
            GlobalEnvVars.ipServer = txtServer.getText().toString();
            GlobalEnvVars.isUnicast = rbUnicast.isSelected();
            if (rbMulticast.isSelected())
            {
                GlobalEnvVars.BindInterface = txtBindInterface.getText();
            }

            dispose();
        }
        writeToFile("conn_rec.txt", GlobalEnvVars.ipServer, Integer.toString(GlobalEnvVars.port), GlobalEnvVars.BindInterface, GlobalEnvVars.isUnicast);
    }

    /**
     * action untuk btnCancel
     */
    @Action
    public void clickCancel()
        {dispose();}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JRadioButton rbMulticast;
    private javax.swing.JRadioButton rbUnicast;
    private javax.swing.JTextField txtBindInterface;
    private javax.swing.JTextField txtPort;
    private javax.swing.JTextField txtServer;
    // End of variables declaration//GEN-END:variables
}
